<template>
	<view>
		<cu-page-bg></cu-page-bg>
		<view class="cu-w-100">
			<cu-navbar title="账本管理" :placeholder="true" @leftClick="vk.navigateBack()" :showLeft="true"
				:leftIconColor="{color:backgroundStyle.color}" :titleStyle="{color:backgroundStyle.color}"
				:style="getBackgroundStyle" bgColor="rgb(255,255,255,0)"></cu-navbar>
			<view class="cu-w-100 cu-p-20 cu-border-box">
				<view v-if="accountBooks === undefined || accountBooks.length === 0" class="cu-w-100 cu-py-20">
					<cu-card :style="cardStyle1">
						<u-empty mode="data" text="还没有账本,快来添加吧"></u-empty>
					</cu-card>
				</view>

				<view v-else class="cu-w-100 cu-py-20 cu-text-white">
					<block v-for="(item,idx) in accountBooks" :key="idx">
						<cu-card :key="idx" :style="idx % 2 == 0 ? cardStyle2 : cardStyle">
							<view class="cu-w-100 cu-row cu-j-sb cu-py-10">
								<view class="cu-font-weight cu-text-info">
									<u-tag :text="item.accountType % 2 == 0 ? '共享账本' : '个人账本'" plain size="mini"
										shape="circle"
										:type="item.accountType % 2 == 0 ? 'success' : 'primary'"></u-tag>
								</view>
								<view @click="itemClick(idx)"><u-icon name="list-dot" color="#FFF" size="24"></u-icon>
								</view>
							</view>
							<view class="cu-font-weight cu-py-10" style="font-size: 32px;">{{item.accountBookName}}
							</view>
							<view class="cu-py-10 cu-text-light-muted">{{item.remarks}}</view>
							<view class="cu-w-100 cu-row cu-j-sb cu-py-10">
								<view>共 <span class="cu-text-info">{{item.totalPersion}}</span> 人记账</view>
								<view>创建时间：<span class="cu-text-info">{{item.createTime | formatDate}}</span></view>
							</view>
						</cu-card>
					</block>

					<view v-if="accountBooks.length > 2" class="cu-my-40">
						<u-loadmore :status="loadMore.status" :loading-text="loadMore.loadingText" :loadmore-text="loadMore.loadmoreText"
							:nomore-text="loadMore.nomoreText" :color="main" :lineColor="main" line/>
					</view>
				</view>
				<view class="cu-w-100 cu-py-20">
					<view class="cu-w-100 cu-row  cu-j-center">
						<u-button shape="circle" text="添加账本"
							@click="insertAccountBookBtn()"
							color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
							:customStyle="{width:'100%'}"></u-button>
					</view>
				</view>
			</view>
		</view>
		<u-popup :show="show" mode="left" @close="close" @open="open" :customStyle="{width:'150%'}">
			<view class="cu-pt-50 cu-mt-50">
				<view class="cu-font-weight cu-px-20">{{accountBook.accountBookName}}</view>
				<cu-card>
					<u-cell-group :border="false">
						<u-cell title="编辑" @click="vk.myfn.gotoPage('/pages/accountbook/update/index','navigate')">
							<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-bianji"></cu-icon>
						</u-cell>
						<u-cell title="成员管理" :border="false"
							@click="cyglBtn()">
							<cu-icon custom-prefix="iconfont" slot="icon" size="24"
								name="icon-gerenzhongxin_chengyuanguanli"></cu-icon>
							<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
						</u-cell>
					</u-cell-group>
				</cu-card>
				<cu-card :style="cardStyle1">
					<u-cell-group :border="false">
						<u-cell title="流水" :border="false"
							@click="vk.myfn.gotoPage('/pages/accountbook/turnover/index','navigate')">
							<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-liushuimingxi"></cu-icon>
							<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
						</u-cell>
						<u-cell title="图表" :border="false">
							<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-caisetubiao"></cu-icon>
							<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
						</u-cell>
						<u-cell title="导出" :border="false">
							<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-daochu"></cu-icon>
							<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
						</u-cell>
					</u-cell-group>
				</cu-card>
				<cu-card :style="cardStyle1">
					<u-cell-group :border="false">
						<u-cell title=" 删除" :border="false" @click="clickCardItem('delAccountBook')">
							<cu-icon slot="icon" size="24" custom-prefix="iconfont" name="icon-shanchu"></cu-icon>
						</u-cell>
					</u-cell-group>
				</cu-card>
			</view>
		</u-popup>

		<u-modal :show="showModal" @close="closeModal" @cancel="closeModal" @confirm="confirmModal" ref="uModal"
			:title="modal.title" :content='modal.content' :zoom="true" :showCancelButton="true"
			:closeOnClickOverlay="true"></u-modal>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		computed: {
			getBackgroundStyle() {
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			},
			accountBooks() {
				let accountbooks = []
				this.enqrDataByPage = vk.getVuex('$accountbook.enqrDataByPage')
				accountbooks = this.enqrDataByPage.data || []
				if(this.enqrDataByPage && this.enqrDataByPage.hasMore) {
					this.loadMore.status = "loadmore"
				}
				else {
					this.loadMore.status = " nomore"
				}
				return accountbooks
			},
		},
		filters: {
			formatDate(value) {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				});
			}
		},
		data() {
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				buttonColor: "linear-gradient(to right, " + vk.getVuex('$app.color.main') + "," + vk.getVuex(
					'$app.color.secondary') + ")",
				cardStyle1: {
					"marginTop": "20rpx",
				},
				cardStyle: {
					"marginTop": "20rpx",
					"background": "url(/pages/accountbook/static/111.png)"
				},
				cardStyle2: {
					"marginTop": "20rpx",
					"background": "url(/pages/accountbook/static/222.png)"
				},
				backgroundStyle: {
					color: "#FFF"
				},
				show: false,
				accountBook: undefined,
				showModal: false,
				modelType: "",
				modal: {
					title: '温馨提示',
					content: '确认删除么？'
				},
				enqrDataByPage: vk.getVuex('$accountbook.enqrDataByPage'),
				loadMore: {
					status: 'loadmore',
					loadingText: '努力加载中',
					loadmoreText: '上拉加载更多',
					nomoreText: '实在没有了'
				},
				selectIndex: undefined
			};
		},
		onLoad(options) {
			vk = uni.vk;
			this.init(options);
		},
		// 上拉触底事件
		onReachBottom() {
			if (!this.enqrDataByPage.hasMore) return; // 无更多数据时直接返回
			let that = this
			this.loadMore.status = "loading"
			this.enqrAccountBook()
		},
		onShow(){
			this.$store.dispatch('$accountbook/clearEnqrData');
			this.reloadData();
			this.show = false
		},
		onShareAppMessage(res) {
		    return {
		      title: this.userInfo.nickname + '邀请你，快来加入【' + this.accountBook.accountBookName + "】一起记账吧！",
		      path: '/pages/index/index?bookId=' + this.accountBook._id
		    }
		},
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
				// 获取已存在信息
				this.enqrDataByPage = vk.getVuex('$accountbook.enqrDataByPage') || null;
			},
			reloadData(){
				// 获取已存在信息
				this.enqrDataByPage = vk.getVuex('$accountbook.enqrDataByPage') || null;
				// console.log("this.enqrDataByPage",this.enqrDataByPage)
				if (this.enqrDataByPage && (this.enqrDataByPage.data == null || this.enqrDataByPage.data.length == 0)) {
					// 查询账本信息
					this.enqrAccountBook()
				}
				if(this.selectIndex != undefined) {
					this.initSelectAccountBook(this.selectIndex);
				}
			},
			itemClick(index) {
				this.show = true
				this.selectIndex = index
				this.initSelectAccountBook(index);
				vk.setVuex('$accountKeepData.selectAccountBookIndex', index);
			},
			// 设置选中账本
			initSelectAccountBook(index){
				const accountBook = this.accountBooks[index]
				this.accountBook = accountBook
				this.$store.dispatch('$accountbook/selectAccountBook', {accountBook});
			},
			open() {},
			close() {
				this.show = false
				this.selectIndex = undefined
			},
			clickCardItem(type) {
				if (type && type === 'delAccountBook') {
					this.modelType = "delAccountBook";
					this.modal.content = "确认删除" + this.accountBook.accountBookName + "么？";
					this.showModal = true;
				}
			},
			closeModal() {
				this.showModal = false;
			},
			confirmModal() {
				if (this.modelType === "delAccountBook") {
					this.delAccountBook()
				}
			},
			// 删除账本
			async delAccountBook() {
				const that = this
				await vk.callFunction({
					url: 'client/accountbook/kh/delAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						accountBook: that.accountBook
					},
					success: (res) => {
						// 重置账本数据，进行查询
						that.$store.dispatch('$accountbook/clearEnqrData');
						that.close();
						that.closeModal();
						that.reloadData();
					},
					fail: (err) => {
						const msg = "删除失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			// 新增账本
			insertAccountBookBtn(){
				this.$store.dispatch('$accountbook/clearSelectAccountBook');
				vk.navigateTo("/pages/accountbook/update/index");
			},
			async enqrAccountBook() {
				let that = this
				const pagination = {
					"pageIndex": vk.getVuex('$accountbook.enqrDataByPage.pagination.pageIndex') + 1,
					"pageSize": vk.getVuex('$accountbook.enqrDataByPage.pagination.pageSize')
				}
				await vk.callFunction({
					url: 'client/accountbook/kh/enqrAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination
					},
					success: (res) => {
						this.$store.dispatch('$accountbook/enqrAccountBook', {
							res
						});
					},
					fail: (err) => {
						const msg = "查询失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			cyglBtn(){
				if (this.accountBook && !(this.accountBook.accountType == "2" || this.accountBook.accountType == 2)) {
					vk.alert("当前账本非共享账本-请修改账本类型后尝试", "错误提示");
					return
				}
				vk.navigateTo("/pages/accountbook/member/index");
			}
		}
	};
</script>

<style lang="scss" scoped>

</style>